package com.sino.androiddesign.recyclerviewdemo


import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.StaggeredGridLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout

import com.sino.androiddesign.R
import kotlinx.android.synthetic.main.fragment_grid_pool.*
import java.lang.NullPointerException


/**
 * 网格瀑布流
 *  实现 和普通list 的转换
 */
class GridPoolFragment : Fragment() {

    private var datas: IntArray = intArrayOf(R.mipmap.ic01, R.mipmap.ic02, R.mipmap.ic03, R.mipmap.ic04,R.mipmap.ic05,R.mipmap.ic06)

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_grid_pool, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        var countData: ArrayList<Int> = ArrayList();
        for (i in 0 until 42) {
            countData.add(datas[i % datas.size])
        }
        var gridAdapter: GridPoolAdapter = GridPoolAdapter(context!!, countData)
        var gridItemDivider = GridItemDivider(context!!, GridItemDivider.line_horizontal)

        normal_btn.setOnClickListener {

            var linearLayoutManager = LinearLayoutManager(context)
            linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
            layout_rv.layoutManager = linearLayoutManager
            layout_rv.adapter = gridAdapter
            layout_rv.addItemDecoration(gridItemDivider)

        }

        grid_btn.setOnClickListener {
            var gridLayoutManager: GridLayoutManager = GridLayoutManager(context!!, 4)
            layout_rv.layoutManager = gridLayoutManager
            layout_rv.adapter = gridAdapter
            layout_rv.removeItemDecoration(gridItemDivider)
            gridAdapter.notifyDataSetChanged()

        }

        pool_btn.setOnClickListener {
            var staggeredGridLayoutManager = StaggeredGridLayoutManager(7, LinearLayout.VERTICAL)
            layout_rv.layoutManager = staggeredGridLayoutManager
            layout_rv.adapter = gridAdapter
            layout_rv.removeItemDecoration(gridItemDivider)
            gridAdapter.notifyDataSetChanged()
        }


    }

}

class GridPoolAdapter(private val mContext: Context, var count: ArrayList<Int>) : RecyclerView.Adapter<GridPoolHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GridPoolHolder {
        var inflate = LayoutInflater.from(mContext).inflate(R.layout.fragment_grid_pool_item_layout, parent, false)
        var gridPoolHolder = GridPoolHolder(inflate)
        gridPoolHolder.bindView(inflate)
        return gridPoolHolder
    }

    override fun getItemCount(): Int {
        return count.size
    }

    override fun onBindViewHolder(holder: GridPoolHolder, position: Int) {
        holder.imageView.setImageResource(count[position])
    }
}

class GridPoolHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
    lateinit var imageView: ImageView
    fun bindView(itemView: View?) {
        imageView = itemView!!.findViewById(R.id.grid_item_iv)
    }
}

class GridItemDivider : RecyclerView.ItemDecoration {

    companion object {
        const val line_vertical = 1   //竖线
        const val line_horizontal = 0  //横线
    }

    private lateinit var mDrawer: Drawable

    private lateinit var context: Context

    private var rect: Rect = Rect()   //边框

    private var orientation: Int = line_horizontal

    constructor(mContext: Context, orientation: Int) {
        if ((orientation != line_horizontal) and (orientation != line_vertical)) {
            throw NullPointerException("方向错误")
        }
        mDrawer = if (orientation == line_vertical) {
            mContext.getDrawable(R.drawable.shape_w1)
        } else {
            mContext.getDrawable(R.drawable.shape_h1)
        }
        this.orientation = orientation
        this.context = mContext
    }

    override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) {
        if (orientation == line_horizontal) {
            outRect!!.set(0, 5, 0, mDrawer.intrinsicHeight + 5)
        } else {
            outRect!!.set(5, 0, mDrawer.intrinsicWidth + 5, 0)
        }
    }

    override fun onDraw(c: Canvas?, parent: RecyclerView?, state: RecyclerView.State?) {
        super.onDraw(c, parent, state)
        c!!.save()

        if (orientation == line_horizontal) {   //画横线

            var left: Int = 0
            var right: Int = 0
            if (parent!!.clipToPadding) {
                left = parent.paddingLeft
                right = parent.right - parent.paddingRight
                c.clipRect(left, parent.paddingTop, right, parent.height - parent.paddingBottom)
            }
            for (i in 0 until parent.childCount) {
                var child: View = parent.getChildAt(i)
                parent.getDecoratedBoundsWithMargins(child, rect)  //获得边缘装饰边界
                var bottom: Int = rect.bottom + Math.round(child.translationY)
                var top: Int = bottom - mDrawer.intrinsicHeight
                mDrawer.setBounds(left, top, right, bottom)
                mDrawer.draw(c)

            }
        }

        if (orientation == line_vertical) {
            var top: Int = 0
            var bottom: Int = 0
            if (parent!!.clipToPadding) {
                top = parent.paddingTop
                bottom = parent.bottom - parent.paddingBottom
                c.clipRect(parent.left, top, parent.right - parent.paddingRight, bottom)
            }
            for (i in 0 until parent.childCount) {
                var childView = parent.getChildAt(i)

                parent.getDecoratedBoundsWithMargins(childView, rect)
                var right: Int = rect.right + Math.round(childView.translationX)
                var left: Int = right - mDrawer.intrinsicWidth
                mDrawer.setBounds(left, top, right, bottom)
                mDrawer.draw(c)
            }
        }

        c.restore()
    }
}
// todo 为 网格添加分割线
class DividerGridItemDecoration :RecyclerView.ItemDecoration{
    companion object {
        val attrInt:IntArray = intArrayOf(android.R.attr.listDivider)
    }

   private lateinit  var mDrawable :Drawable

    constructor(mContext: Context){
        var attributes = mContext.obtainStyledAttributes(attrInt)
        mDrawable = attributes.getDrawable(0)
        attributes.recycle()

    }

    override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) {
        var spanCount = getSpanCount(parent!!)
        var childCount:Int = parent.adapter.itemCount

    }


    override fun onDraw(c: Canvas?, parent: RecyclerView?, state: RecyclerView.State?) {
        super.onDraw(c, parent, state)

    }

    fun getSpanCount(recyclerView: RecyclerView):Int{
        var layoutManager = recyclerView.layoutManager
        if (layoutManager is GridLayoutManager){
            return  layoutManager.spanCount
        }else if (layoutManager is StaggeredGridLayoutManager){
            return layoutManager.spanCount
        }else{
            return  -1
        }
    }

    fun isFirstRaw(recyclerView: RecyclerView,position: Int,spanCount:Int,childCount:Int):Boolean{

        var layoutManager = recyclerView.layoutManager
        if (layoutManager is GridLayoutManager){
            var currentCount = childCount -childCount%spanCount
        }

        return true
    }

}